package com.wing.cabinet.controller.app;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.cabinet.model.entity.CellInventoryOutAmount;
import com.wing.cabinet.model.entity.StorageInventoryKnife;
import com.wing.cabinet.model.entity.StorageInventorySpace;
import com.wing.cabinet.model.request.StorageInventoryKnifeForm;
import com.wing.cabinet.model.response.StorageInventoryKnifeVO;
import com.wing.cabinet.model.response.StorageInventorySpaceVO;
import com.wing.cabinet.model.response.StorageInventoryUserVO;
import com.wing.cabinet.service.CellInventoryOutAmountService;
import com.wing.cabinet.service.StorageInventoryKnifeService;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.setting.model.entity.SystemRuleInfo;
import com.wing.setting.service.SystemRuleInfoService;
import com.wing.web.utils.JwtUtils;
import com.wing.web.utils.LocaleMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "App-刀具产品货道库存管理", tags = "刀具产品货道库存管理")
@RestController("appStorageInventoryKnifeController")
@RequestMapping("cabinet/app/storageInventoryKnife")
public class StorageInventoryKnifeController {

    @Autowired
    private StorageInventoryKnifeService storageInventoryKnifeService;
    @Autowired
    private LocaleMessage localeMessage;

    @Autowired
    private SystemRuleInfoService systemRuleInfoService;

    @Autowired
    private CellInventoryOutAmountService cellInventoryOutAmountService;

    @GetMapping()
    public PageResult<StorageInventoryKnifeVO> list(
            @RequestParam(name = "page", value = "第几页", defaultValue = "1", required = false) Integer page
            ,@RequestParam(name = "limit", value = "每页多少条", defaultValue = "10", required = false) Integer limit
            ,@RequestParam(name = "sort", value="排序字段名", defaultValue = "create_time", required = false) String sort
            ,@RequestParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "desc", required = false) String order
    ) {
        Page<StorageInventoryKnifeVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }

        Page<StorageInventoryKnifeVO> list = storageInventoryKnifeService.pageList4app(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "查询小程序盘验任务商品明细", notes = "搜索")
    @GetMapping("listMini")
    public PageResult<StorageInventoryKnifeVO> listMini(
            @RequestParam(name = "page", defaultValue = "1", required = false) Integer page
            ,@RequestParam(name = "limit", defaultValue = "10", required = false) Integer limit
            ,@RequestParam(name = "sort", defaultValue = "create_time", required = false) String sort
            ,@RequestParam(name = "order", defaultValue = "desc", required = false) String order
            ,String cabCode
            ,String spaceCode
            ,String mainCabCode
    ) {
        Page<StorageInventoryKnifeVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }

        params.put("cabCode4Detail",cabCode);
        params.put("spaceCode4Detail",spaceCode);
        if (StringUtils.isNotBlank(mainCabCode)){
            params.put("mainCabCode",mainCabCode);
        }

        Page<StorageInventoryKnifeVO> list = storageInventoryKnifeService.pageList4app(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "小程序盘验，扫描唯一码", notes = "查询")
    @GetMapping("scanLabelCode")
    public JsonResult scanLabelCode(String labelCode){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("label_code",labelCode);
        StorageInventoryKnife storageInventoryKnife = storageInventoryKnifeService.getOne(queryWrapper);
        return JsonResult.success(storageInventoryKnife);
    }

    @ApiOperation(value = "查询暂存柜库位上库存（柜子面板上）", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "productCategoryId", value = "产品分类id", defaultValue = "", example = "", dataType = "Long", paramType = "query")
            ,@ApiImplicitParam(name = "productTypeId", value = "产品类型id", defaultValue = "", example = "", dataType = "Long", paramType = "query")
            ,@ApiImplicitParam(name = "skuName", value = "SKU名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "brandName", value = "品牌名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "typeName", value = "产品类型名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "cabCodes", value = "柜子编号", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list4Cab")
    public PageResult<StorageInventoryKnifeVO> list4Cab(
            @RequestParam(name = "page",  defaultValue = "1", required = false) Integer page
            ,@RequestParam(name = "limit",  defaultValue = "10", required = false) Integer limit
            ,@RequestParam(name = "sort",  defaultValue = "create_time", required = false) String sort
            ,@RequestParam(name = "order",  defaultValue = "desc", required = false) String order
            ,Long productCategoryId
            ,Long productTypeId
            ,String cabCodes
            ,String skuName
            ,String brandName
            ,String typeName
            ,String name
            ,String spaceCode
            ,String cabCode
    ) {
        Page<StorageInventoryUserVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        params.put("productCategoryId",productCategoryId);
        params.put("productTypeId",productTypeId);
        if (StringUtils.isNotBlank(cabCodes)){
            String [] cabCodeArray=cabCodes.split(",");
            params.put("cabCodes",cabCodeArray);
        }
        params.put("skuName",skuName);
        params.put("brandName",brandName);
        params.put("typeName",typeName);
        params.put("name",name);
        params.put("spaceCode4Detail",spaceCode);
        params.put("cabCode",cabCode);
        Page<StorageInventoryKnifeVO> list = storageInventoryKnifeService.pageList4app(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "查询暂存柜库位上库存（Wx）", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "productCategoryId", value = "产品分类id", defaultValue = "", example = "", dataType = "Long", paramType = "query")
            ,@ApiImplicitParam(name = "productTypeId", value = "产品类型id", defaultValue = "", example = "", dataType = "Long", paramType = "query")
            ,@ApiImplicitParam(name = "skuName", value = "SKU名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "brandName", value = "品牌名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "typeName", value = "产品类型名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "cabCodes", value = "柜子编号", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list4Wx")
    public PageResult<StorageInventoryKnifeVO> list4Wx(
            @RequestParam(name = "page",  defaultValue = "1", required = false) Integer page
            ,@RequestParam(name = "limit",  defaultValue = "10", required = false) Integer limit
            ,@RequestParam(name = "sort",  defaultValue = "create_time", required = false) String sort
            ,@RequestParam(name = "order",  defaultValue = "desc", required = false) String order
            ,Long productCategoryId
            ,Long productTypeId
            ,String cabCodes
            ,String skuName
            ,String brandName
            ,String typeName
            ,String name
            ,String spaceCode
            ,String cabCode
    ) {
        Page<StorageInventoryUserVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        params.put("productCategoryId",productCategoryId);
        params.put("productTypeId",productTypeId);
        if (StringUtils.isNotBlank(cabCodes)){
            String [] cabCodeArray=cabCodes.split(",");
            params.put("cabCodes",cabCodeArray);
        }
        params.put("skuName",skuName);
        params.put("brandName",brandName);
        params.put("typeName",typeName);
        params.put("name",name);
        params.put("spaceCode4Detail",spaceCode);
        params.put("cabCode",cabCode);
        Page<StorageInventoryKnifeVO> list = storageInventoryKnifeService.pageList4app(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @GetMapping("/storage/listOut")
    @ApiOperation(value = "取暂存刀列表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "name", value = "名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    public PageResult<StorageInventoryKnifeVO> listOut(
            @RequestParam(name = "page",defaultValue = "1") Integer page
            ,@RequestParam(name = "limit",defaultValue = "10") Integer limit
            ,@RequestParam(name = "sort",defaultValue = "id") String sort
            ,@RequestParam(name = "order",defaultValue = "asc") String order
            ,String cabCode
            ,String deviceCode
            ,Long productCategoryId
            ,Long productTypeId
            ,String cabCodes
            ,String skuName
            ,String brandName
            ,String typeName
            ,String name
            ,String labelCode
            ,String flag
            ,Long workOrderId
            ,Long creatorId
            ,String deviceCode4Query
            ,Long brandId
            ,Long processId
            ,String startCreateTime
            ,String endCreateTime
    ) {
        Page<StorageInventorySpaceVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        params.put("businessType", StorageInventorySpace.BusinessType.temp.getValue());
        params.put("cabinetCode",cabCode);
        params.put("productCategoryId",productCategoryId);
        params.put("productTypeId",productTypeId);
        if (StringUtils.isNotBlank(cabCodes)){
            String [] cabCodeArray=cabCodes.split(",");
            params.put("cabCodes",cabCodeArray);
        }
        params.put("skuName",skuName);
        params.put("brandName",brandName);
        params.put("typeName",typeName);
        params.put("name",name);
//        params.put("deviceCode",deviceCode);
        //params.put("loginUserId", JwtUtils.getLoginUserId());
        params.put("labelCode",labelCode);
        params.put("flag",flag);
        params.put("userId", JwtUtils.getLoginUserId());
        params.put("workOrderId",workOrderId);
        params.put("creatorId",creatorId);
        params.put("deviceCode4Query",deviceCode4Query);
        params.put("brandId",brandId);
        params.put("processId",processId);
        params.put("startCreateTime",startCreateTime);
        params.put("endCreateTime",endCreateTime);
        Page<StorageInventoryKnifeVO> list = storageInventoryKnifeService.pageList4app(pg, params);
        PageResult pageResult=new PageResult<>(list.getRecords(), list.getTotal());
//        List<SystemRuleInfo> systemRuleInfos=systemRuleInfoService.list();
        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getRuleInfo();
        if (systemRuleInfo!=null){
            Boolean showPriceFlag=systemRuleInfo.getShowPriceFlag();
            pageResult.setTotalFlag(systemRuleInfo.getTotalFlag());
            if(systemRuleInfo.getTotalFlag()&&systemRuleInfo.getTotal()!=null&&systemRuleInfo.getTotal().doubleValue()>0){
                List<CellInventoryOutAmount> cellInventoryOutAmounts=cellInventoryOutAmountService.list(new QueryWrapper<CellInventoryOutAmount>().eq("creator", JwtUtils.getLoginUserId()));
                if (cellInventoryOutAmounts.size()>0){
                    pageResult.setCurrentTotal(cellInventoryOutAmounts.get(0).getTotal());
                }else{
                    pageResult.setCurrentTotal(BigDecimal.valueOf(0));
                }
                pageResult.setSettingTotal(systemRuleInfo.getTotal());
            }
            list.getRecords().forEach(item->{
                item.setShowPriceFlag(showPriceFlag);
            });
        }
        return pageResult;
    }

    @GetMapping("/detail/{id}")
    public JsonResult detail(@PathVariable("id") Long storageInventoryKnifeId) {
        StorageInventoryKnifeVO storageInventoryKnifeVO = storageInventoryKnifeService.get4appById(storageInventoryKnifeId);
        if (storageInventoryKnifeVO == null) {
            return JsonResult.fail(localeMessage.getMessage("common.fail"));
        }
        return JsonResult.success(localeMessage.getMessage("common.success"), storageInventoryKnifeVO);
    }

    @PostMapping()
    public JsonResult add(@Validated StorageInventoryKnifeForm storageInventoryKnifeForm) {
        if (storageInventoryKnifeService.add(storageInventoryKnifeForm) > 0) {
            return JsonResult.success(localeMessage.getMessage("common.success"));
        }
        return JsonResult.fail(localeMessage.getMessage("common.fail"));
    }

    @ApiOperation(value = "取刀不一致修改备注", notes = "修改")
    @GetMapping("/updateRemark")
    public JsonResult updateRemark(Long id,String remark){
        StorageInventoryKnife storageInventoryKnife=new StorageInventoryKnife();
        storageInventoryKnife.setId(id);
        storageInventoryKnife.setKnifeRemark(remark);
        storageInventoryKnifeService.updateById(storageInventoryKnife);
        return JsonResult.success();
    }

}
